// iplookup.cpp
// Given a domain name, this program sends a query to DNS and displays the IP address returned.

#include <iostream>
#include <iomanip>
#include <winsock2.h>
using namespace std;
#pragma comment (lib,"ws2_32.lib")

int main (int argc, char **argv)
{
	char			host[128];		// This string contains the name of desired remote machine
	struct			hostent *phe;	// pointer to host information entry
	unsigned long	ihost;			// 32-bit address (Network Byte Order) of remote machine

	if (argc < 2)
	{
		cout << "Please specify a host." << endl;
		return 0;
	}
	strcpy_s(host, sizeof(host), argv[1]);

	// Initialize Winsock
	WORD wVersion = 0x0202;
	WSADATA wsaData;
	int iResult = WSAStartup(wVersion, &wsaData);  // Returns zero if successful
	if (iResult != 0) {
		cout << "Insufficient resources to startup WINSOCK." << endl;
		return 0;
	}


	ihost = inet_addr(host);	// 1st try to convert "dotted decimal" to 32-bit integer
	if (ihost == INADDR_NONE) {	// If that doesn't work, send the hostname to DNS
		phe = gethostbyname(host);
		if (phe)
		{
			memmove(&ihost, phe->h_addr, phe->h_length);
		}
		else
		{
			cout << "Could not find host." << endl;
			return INVALID_SOCKET;
		}
	}

	cout << "Network address for hostname:         " << host << endl;
	cout << "32-bit address in Network Byte Order: " << ihost << " = 0x" << setbase(16) << ihost << endl;

	unsigned long HostByteOrder_ihost = ntohl(ihost);
	cout << "32-bit address in Host Byte Order:    " << setbase(10) << HostByteOrder_ihost << " = 0x" 
		 << setbase(16) << HostByteOrder_ihost << endl;

	struct in_addr in;
	in.S_un.S_addr = ihost;
	cout << "Address as dotted decimal:            " << inet_ntoa(in) << endl;

}